import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { message } from 'antd';
import 'antd/lib/message/style';
import LoginFooter from '../Login_Footer';
import {
  COMMON_SUCCESS_STATE, PAN_PATH_HOME,
  SMS_LOGIN_PATH
} from '../../../constant';
import { verifyPassword, verifyPhone, verifyUsername } from '../../../utils/verify';
import { login } from '../../../api';
import './index.less';

class Modal_Login extends PureComponent {

  static propTypes = {
    history: PropTypes.object
  };

  state = {
    loginObject: {
      username: '',
      password: '',
    },
    loginTip: '',
  };

  // 跳转短信登录页面
  skipSMSLogin = () => {
    this.props.history.push(SMS_LOGIN_PATH);
  };

  // input 受控组件
  inputLoginObject = (type, event) => {
    const { loginObject } = this.state;
    loginObject[type] = event.target.value;
    this.setState({
      loginObject: JSON.parse(JSON.stringify(loginObject)),
    });
  };

  // 登录
  login = async () => {
    const {
      loginObject: {
        username,
        password
      }
    } = this.state;
    let tip = '';
    if (!username) {
      tip = '请输入手机/邮箱/用户名';
    } else if (!password) {
      tip = '请输入密码';
    } else if (!verifyUsername(username) && !verifyPhone(username)) {
      tip = '用户名格式不正确(支持用户名/手机号)';
    } else if (!verifyPassword(password)) {
      tip = '密码不符合要求';
    }
    // 设置提示信息
    if (tip) {
      this.setState({
        loginTip: tip,
      });
      return;
    }
    // 登录
    const {
      code,
      msg
    } = await login({
      username,
      password
    });
    if (code === COMMON_SUCCESS_STATE) {
      message.success('登录成功');
      // 跳转网盘页面
      this.props.history.replace(PAN_PATH_HOME);
    } else {
      message.error(msg);
    }
  };

  render () {
    const { loginTip } = this.state;

    return (
      <>
        <div className="login">
          <div className="login_title">
            <span>
                账号密码登录
            </span>
            <span>
              <a href="#" onClick={this.skipSMSLogin}>
                  短信快捷登录&gt;
              </a>
            </span>
          </div>
          <p className="login_tip">
            {
              loginTip
            }
          </p>
          <div className="login_input">
            <input
              type="text"
              onInput={(event) => this.inputLoginObject('username', event)}
              name="username"
              placeholder="手机/邮箱/用户名"
            />
            <input
              type="password"
              onInput={(event) => this.inputLoginObject('password', event)}
              name="password"
              placeholder="密码"
            />
          </div>
          <div className="login_button">
            <input type="submit" value="登录" onClick={this.login}/>
          </div>
          <div className="login_tool">
            忘记密码？
          </div>
          <LoginFooter/>
        </div>
      </>
    );
  }
}

export default Modal_Login;
